<template>
    <div style="margin: 48px auto; width: 50vw;">
        <div style="display: flex; flex-direction: column;">
            <div style="flex: 1">
                <video ref="videoRef" controls @ended="onend" style="width: 100%; height: 100%;">
                    <source :src="video_src" type="video/mp4">
                    您的浏览器不支持 HTML5 视频标签。
                </video>
            </div>


            <div style="flex-shrink: 0; align-items: center; justify-content: end" class="flex-row-gap">
                <div>总时长：{{ formatTime(duration) }}</div>
                <div>缓存至：{{ formatTime(buffered) }}</div>
                <div>观看至：{{ formatTime(currentTime) }}</div>
            </div>
            <div style="height: 32px; flex-shrink: 0; align-items: center" class="flex-row-gap">
                <input ref="inputRef" type="range" class="slider" min="0" max="100" value="50" step="1"
                       style="cursor: pointer"  @input="onSlideInput" @change="onSlideChange">
            </div>
            <div style="flex-shrink: 0;" class="flex-row-gap">
                <el-button v-for="(item, idx) in list" @click="play(idx)" :key="idx"
                           :type="item.active?'primary':''">
                    视频1 <i class="fa fa-fw fa-dot-circle-o" v-show="item.active"></i>
                </el-button>
                <div class="align-right">
                    <el-button plain type="primary" @click="togglePlay">
                        <i v-show="is_playing" class="fa fa-pause"></i>
                        <i v-show="!is_playing" class="fa fa-play"></i>
                    </el-button>
                    <sea-select style="width: 100px;" :options="options"
                                v-model="playbackRate"></sea-select>
                </div>
            </div>
        </div>
    </div>
</template>

<script setup lang="ts">
import {onMounted, reactive, ref} from "vue";
import useVideo from "@/view/media/use-video";

const {setVideo, bindEvent, unbindEvent, togglePlay, toggleMute, toggleFullscreen, formatTime} = useVideo();

const videoRef = ref();

// 视频时长
const duration = ref(0);
// 已播放时长
const currentTime = ref(0);
// 缓存时长
const buffered = ref(0);
// 播放倍速
const playbackRate = ref(0);
// 是否正在播放
const is_playing = ref(false);

const list = reactive([
    {src: 'http://localhost:7081/sea/sys/video/demo?index=0', active: true}
    , {src: 'http://localhost:7081/sea/sys/video/demo?index=1', active: false}
    , {src: 'http://localhost:7081/sea/sys/video/demo?index=2', active: false}
])


const options = [
    {value: 1, label: '1倍速', style: ''}
    , {value: 1.5, label: '1.5倍速', style: ''}
    , {value: 2, label: '2倍速', style: ''}
    , {value: 3, label: '3倍速', style: ''}
    , {value: 5, label: '5倍速', style: ''}
];

const video_src = ref('');

let curren_index = 0;
const play = (idx) => {
    duration.value = 0;
    currentTime.value = 0;
    buffered.value = 0;

    const post = list[curren_index];
    const curr = list[idx];

    post.active = false;
    curr.active = true;
    curren_index = idx;

    const video = videoRef.value;

    video.src = curr.src;

    video.play()
            .then(() => {
                duration.value = video.duration;
                playbackRate.value = video.playbackRate;
            })
            .catch(error => console.error('播放失败:', error));
}

const onend = (evt) => {
    console.log('视频播放结束');
    // 在这里添加播放结束后的逻辑
    if (curren_index < list.length) {
        const next = curren_index + 1;
        play(next);
    }
}

const inputRef = ref();

/**
 * 滚动条拖动事件
 *
 * @param evt -
 */
const onSlideInput = (evt) => {
    const video = videoRef.value;

    const percentage = Number(evt.target.value);
    video.currentTime = duration.value * percentage / 100;

    changeBar();
}
/**
 * 滚动条值变化事件
 *
 * @param evt -
 */
const onSlideChange = (evt) => {
    const video = videoRef.value;
    changeBar();
}

/**
 * 更新进度条的样式
 */
const changeBar = ()=>{
    const percentage = (currentTime.value / duration.value * 100).toFixed();
    const buffered_ = (buffered.value / duration.value * 100).toFixed();
    inputRef.value.value = percentage;
    inputRef.value.style.background = `linear-gradient(to right, #4CAF50 0%, #4CAF50 ${percentage}%, #DD0 0%, #DD0 ${buffered_}%, #F5F5F5 ${percentage}%, #F5F5F5 100%)`;
}


onMounted(() => {

    const video = videoRef.value;

    // 监听 progress 事件（缓冲进度变化时触发）
    video.addEventListener('progress', () => {
        if (video.buffered.length > 0) {
            // 已缓冲的时长（秒）
            buffered.value = video.buffered.end(0)
        }
    });

    // 监听 timeupdate 事件
    video.addEventListener('timeupdate', () => {
        // 当前播放进度
        currentTime.value = video.currentTime;

        changeBar();
    });


    // 监听 ratechange 事件
    video.addEventListener('ratechange', () => {
        playbackRate.value = video.playbackRate;
    });

    // 监听 play 事件（开始播放或恢复播放）
    video.addEventListener('play', () => {
        console.log('play');
        is_playing.value = true;
    });

    // 监听 pause 事件（暂停）
    video.addEventListener('pause', () => {
        console.log('pause');
        is_playing.value = false;
    });

    setVideo(video);
})

</script>

<style lang="scss" scoped>
</style>